package net.tv90.bfmccore.util.HUD;

import lombok.var;
import org.bukkit.entity.Player;

import java.util.concurrent.*;

public class HUDDelayedQueue {

    //储存玩家的HUD消息队列
    public static volatile ConcurrentHashMap<String, ConcurrentLinkedQueue<HUD>> HUDs = new ConcurrentHashMap<>();

    public static ExecutorService hud_pool = Executors.newFixedThreadPool(10);

    /**
     * 添加一条HUD到队列中，并有序显示给玩家
     *
     * @param p   玩家
     * @param hud HUD
     */
    public static void addHUD(Player p, HUD hud) {
        try {
            //将HUD放入队列中
            ConcurrentLinkedQueue<HUD> list = HUDs.getOrDefault(p.getName(), new ConcurrentLinkedQueue<>());
            list.add(hud);
            HUDs.put(p.getName(), list);
            //展示HUD，如果队列中只有一个HUD，就提交给线程池创建线程
            if (list.size() == 1) {
                hud_pool.execute((new Thread(() -> {
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (HUD m_hud : list) {
                        m_hud.show();   //打印HUD
                        list.remove(m_hud);
                        try {
                            Thread.sleep(m_hud.getLastTime() * 1000L);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static class HUDThreadPool {
        public ExecutorService thread_pool;

        public HUDThreadPool(int maxPoolSize, int queueSize) {
            thread_pool = new ThreadPoolExecutor(maxPoolSize, maxPoolSize, 120L, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(queueSize));
        }

        public void execute(Runnable task) {
            thread_pool.execute(task);
        }

    }
}
